from sqlalchemy import Column, Integer, String, Text, ForeignKey

from db_util import Base, Session, engine


class User(Base):
    __tablename__ = 't_user'
    id = Column(Integer, primary_key=True, autoincrement=True)
    uname = Column(String(50), nullable=False, name='name')


class News(Base):
    __tablename__ = 't_news'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(50), nullable=False)
    content = Column(Text, nullable=False)

    # uid = Column(Integer, ForeignKey('t_user.id'))  #默认不让删主表数据
    # uid = Column(Integer, ForeignKey('t_user.id',ondelete='RESTRICT'))
    # uid = Column(Integer, ForeignKey('t_user.id',ondelete='NO ACTION'))
    # uid = Column(Integer, ForeignKey('t_user.id',ondelete='CASCADE')) # 级联删除，发主表的数据被删除，子表的里数据也会删除
    uid = Column(Integer, ForeignKey('t_user.id',ondelete='SET NULL')) # 发现主表数据被删除时，子表的数据列会清空


def create_data():
    user = User(uname='sxt')
    news1 = News(title='python', content='flask', uid=1)
    news2 = News(title='MySQL', content='SQL', uid=1)

    with Session() as ses:
        ses.add(user)
        ses.commit()
    with Session() as ses:
        ses.add_all([news1,news2])
        ses.commit()

if __name__ == '__main__':
    Base.metadata.create_all(engine)
    create_data()